package com.ifonly.upload;

import com.ifonly.config.Constants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-14 08:49
 * @since JDK 1.6
 */
public abstract class MultipartServletRequest extends HttpServletRequestWrapper {
    protected HttpServletRequest request;

    public MultipartServletRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    private String checkAndCreateDir(File dir){
        if ( !dir.exists()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException("Directory [" + dir.getAbsolutePath() + "] not exists and can not create directory.");
            }
        }

        return dir.getAbsolutePath();
    }

    /**
     * 添加对相对路径的支持
     * 1: 以 "/" 开头或者含有 ":" 的目录被认为是绝对路径
     * 2: 其它路径被认为是相对路径
     */
    protected String handleSaveDirectory(String saveDirectory) {
        if (saveDirectory == null) {
            saveDirectory = request.getServletContext().getRealPath(Constants.IFONLY_SAVE_DIR);
        }
        if (saveDirectory.startsWith("/") || saveDirectory.indexOf(":") == 1) {
            File dir = new File(saveDirectory);
            return checkAndCreateDir(dir);
        } else {
            File dir = new File(getRequest().getServletContext().getRealPath("/"), saveDirectory);
            return checkAndCreateDir(dir);
        }
    }

    protected boolean isSafeFile(IFile iFile) {
        String fileName = iFile.getFileName().trim().toLowerCase();
        if (fileName.endsWith(".jsp") || fileName.endsWith(".jspx")) {
            boolean b = iFile.getFile().delete();
            if (b) {
                return false;
            } else {
                throw new IllegalArgumentException("Delete the unsafe file["+ fileName +"] failed");
            }
        }
        return true;
    }

    public abstract Enumeration<String> getFileNames();

    public abstract File getFile(String name);

    public abstract File[] getFiles(String name);

    public abstract Enumeration<String> getParameterNames();

    public abstract String getParameter(String name);

    public abstract String[] getParameterValues(String name);

    public abstract Map<String, String[]> getParameterMap();

    public abstract Map<String, IFile[]> getFileMap();


}
